package com.example.yurqi.webviewexample

import android.os.Build
import android.support.annotation.RequiresApi
import android.webkit.WebView
import java.lang.reflect.Method

/**
 * Created by yurqi on 17-10-19.
 */
typealias lambda = ()->Unit
class MyInvoc(var webView: WebView) : java.lang.reflect.InvocationHandler {
    @RequiresApi(Build.VERSION_CODES.KITKAT)
    override fun invoke(proxy: Any?, method: Method, args: Array<out Any>): Any? {



        val callBack = args[args.size - 1] as (String) -> Unit

        var url = "javascript:${method.name}("
        for (i in args.indices) {
            if (i != args.size - 1) {
                var it = args[i]
                when (it) {
                    is String -> {
                        url += "\"$it\""
                    }
                    else -> {
                        url += it
                    }
                }
                url += ","
            }
        }
        if (url.endsWith(",")) {
            url = url.substring(0, url.length - 1)
        }
        url += ")"

        //webView.loadUrl(url)
        webView.evaluateJavascript(url)
        {
            callBack.invoke(it)
        }

        return null

    }


}
